// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require("vscode");
const moment = require("moment");
const service = require("./src/service.js");

let loopTimer = null;

// console.log("🚀 ~ getData:", getData);

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "leek-stock" is now active!');

  // The command has been defined in the package.json file
  // Now provide the implementation of the command with  registerCommand
  // The commandId parameter must match the command field in package.json
  // let disposable = vscode.commands.registerCommand(
  //   "leek-stock.helloWorld",
  //   function () {
  //     // The code you place here will be executed every time your command is executed

  //     // Display a message box to the user
  //     vscode.window.showInformationMessage("Hello World from leek-stock!");
  //   }
  // );
  let stockItems = [];
  let show = true;
  let color = "#ffffff";
  let focusColor = "#ed9db2";

  const generatorItem = list => {
    let count = list.length - stockItems.length;
    if (count > 0) {
      while (--count >= 0) {
        const stockBarItem = vscode.window.createStatusBarItem(
          vscode.StatusBarAlignment.Left,
          3
        );
        stockItems.push(stockBarItem);
      }
    } else if (count < 0) {
      let num = Math.abs(count);
      while (--num >= 0) {
        const bar = stockItems.pop();
        bar.hide();
        bar.dispose();
      }
    }
    stockItems.forEach((stock, index) => {
      updateBarInfo(list[index], stock);
    });
  };

  const updateBarInfo = (data, item) => {
    item.id = data.code;
    item.text = `${data.name} ${data.percent}%`;
    item.tooltip = `${data.name} ${data.code.slice(2)}\n现:${
      data.price
    }    参:${data.suggest}%\n高:${data.high}%    低:${data.low}%`;
    const config = vscode.workspace.getConfiguration("leek-stock");
    if (data.suggest === "无") {
      item.color = config.get("color") || color;
    } else {
      if (data.low - data.suggest < 1) {
        if (item.color !== config.get("focusColor")) {
          vscode.window.showInformationMessage(data.volume);
          item.color = config.get("focusColor") || focusColor;
        }
      } else {
        item.color = config.get("color") || color;
      }
    }
    show ? item.show() : item.hide();
  };

  const setIntervalTime = async init => {
    const config = vscode.workspace.getConfiguration("leek-stock");
    const stocks = config.get("stocks");

    const am = moment().isBetween(
      moment().format("YYYY-MM-DD 09:14:56"),
      moment().format("YYYY-MM-DD 11:30:05")
    );
    const pm = moment().isBetween(
      moment().format("YYYY-MM-DD 12:59:56"),
      moment().format("YYYY-MM-DD 15:00:05")
    );

    if (init || ((am || pm) && stocks)) {
      const list = await service.getData(stocks);
      if (list && list.length) {
        generatorItem(list);
      }
    }
  };

  setIntervalTime(true);

  loopTimer = setInterval(setIntervalTime, 3000);

  const disposable = vscode.commands.registerCommand(
    "leek-stock.toggle",
    function () {
      stockItems.forEach(i => {
        show ? i.hide() : i.show();
      });
      show = !show;
    }
  );

  context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
function deactivate() {
  if (loopTimer) {
    clearInterval(loopTimer);
  }
}

module.exports = {
  activate,
  deactivate
};
